#! /usr/bin/env python
#coding:utf-8
from CollectSpider.kancloud import  db
from scrapy.conf import settings
from CollectSpider.globalvar.globalvar import time_list
import time,os,subprocess,platform
from CollectSpider.kancloud.FileUtil import is_None
from CollectSpider.kancloud.PrintMsg import print_msg,unicode_to_str
import types
class Task(object):
        def getAll(self):
            return db.select("select * from spider_task where enabled=1")
        def get_task_by_id(self,taskid):
            return db.select("select * from spider_task where enabled=1 and id=?",taskid)
        
        def get_schedlue(self,taskid):
            return db.select("select time from spider_schedule where task_id=? and flag=0 order by time desc",int(taskid))
        
        def get_search_engine_by_ids(self,ids):
            return db.select("select * from spider_search_engine where id in "+ids)
        def get_search_engine_by_task(self,task):
            if task is not None:
                if int(task["task_type"])==2:
                    search_id=task["search_id"]
                    if search_id is not None:
                        ids=search_id.split(",")
                        list_params=convert_str_tuple(ids)
                        search_engine_list=self.get_search_engine_by_ids(list_params)
                        return search_engine_list
                    else:
                        return None
                else:
                    return None
            else:
                return None

def init_engine():
    print_msg("初始化数据库引擎")
    dbconfig = dict(
              host = settings['DB_HOST'],
              database = settings['DB_DBNAME'],
              port = settings['DB_PORT'],
              user = settings['DB_USER'],
              password = settings['DB_PASSWD'],
              charset = 'utf8',
              use_unicode = True,
            )
    db.create_engine(user=dbconfig["user"],password=dbconfig["password"],database=dbconfig["database"],host=dbconfig["host"],charset=dbconfig["charset"])

def update_taskstatus_by_id(task_id):
    return db.update("update spider_task set task_status=2 where id=?",task_id)
# 检查任务状态
def update_status(task,**kwargs):
    if task is None and type(task)==types.DictType:
        raise ValueError("params error")
    else:
        if(task["task_status"]==2):
            return db.update("update spider_task set task_status=?,pid=?,time_start=?,count_thread=? where id=?",1,kwargs.get("pid"),int(time.time()),1,task['id'])
        elif(task["task_status"]==1):
            return db.update("update spider_task set task_status=?,time_last=?,count_success=?,count_failed=? where id=?",2,int(time.time()),task["count_success"],task.get("count_failed"),task['id'])

# 修改任务运行单次 完成后，状态修改
def update_time_interval(task):
    try:
        if int(task["time_interval"])==0:
            db.update("update spider_task set time_interval=-1 where id=?",task["id"])
    except Exception,e:
        print e

def update_schedule_flag(task,time_run):
    try:
        if int(task["schedule_type"])==2:
            db.update("update spider_schedule set flag=1 where task_id=? and time=?",task["id"],time_run)
    except Exception,e:
        print e
        
def convert_str_tuple(list_param):
    str_s="("
    i=0
    for val in list_param:
        i+=1
        if i==len(list_param):
            str_s+=val
        else:
            str_s+=val
            str_s+=","
    
    str_s+=")"
    return str_s
        
#定天执行任务
def every_day(taskid):
    task=Task()
    nowtime=int(time.time())
    tasklist=task.get_schedlue(taskid)
    timelist=[]
    if is_None(tasklist) is not None:
        for tk in tasklist:
            timelist.append(tk['time'])
        validtimelist=[]
        #删除全部
        del time_list[:]
        for times in timelist:
            if times-nowtime>=0 and times-nowtime<=150: #验证时间是否过时
                validtimelist.append(times)
                time_list.append(int(times))
                
            else:
                print_msg("任务id:%s 的 调度时间点：%s ,还没到，等待执行" % (unicode_to_str(taskid),times))
        return validtimelist
    else:
        print_msg("调度时间 没有设置")
        
def UsePlatform():
    sysstr = platform.system()
    if(sysstr =="Windows"):
        return "Win"
    elif(sysstr == "Linux"):
        return "Linux"
        
def pingServer(server):
    cmd="ping %s" % server
    result=os.system(cmd)
    if result:
        print '服务器%s ping fail' % server
    else:
        print '服务器%s ping ok' % server
    print result

def pingServerCall(server):
    fnull=None
    if UsePlatform()=="Win":
        fnull=open("ping.txt","w")
    else:
        fnull = open(os.devnull, 'w')
    result = subprocess.call('ping '+server+' -c 2', shell = True, stdout = fnull, stderr = fnull)
    if result:
        print '服务器%s ping fail' % server
    else:
        print '服务器%s ping ok' % server
    fnull.close()

if __name__=="__main__":
    init_engine()
    task=Task()
    print task.getAll()[0]
    timelist=task.get_schedlue(16)
    print task.get_search_engine_by_task({"id":18,"task_type":2,"search_id":"1,2"})
    
    pingServerCall("www.baidu.com")
    
    
    
    

